﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using CamPlug.Api;

namespace CamPlugManager
{
	public static class PluginFactoryManager
	{
		public static IPluginFactory[] PluginFactories;
		static string PluginDirectory;

		static PluginFactoryManager()
		{
			var pluginFactories = new List<IPluginFactory>();
			PluginDirectory = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Plugins");
			Directory.CreateDirectory(PluginDirectory);
			LoadPluginFactories(PluginDirectory, pluginFactories);
			PluginFactories = pluginFactories.ToArray();
		}

		static void LoadPluginFactories(string directoryPath, List<IPluginFactory> pluginFactories)
		{
			foreach(string fileName in Directory.GetFiles(directoryPath, "*.Plugin.dll"))
				try
				{
					var assembly = Assembly.LoadFrom(fileName);
					foreach (var currentType in assembly.GetExportedTypes())
						if (
								currentType.IsClass
								&& !currentType.IsAbstract
								&& !currentType.IsGenericType
								&& typeof(IPluginFactory).IsAssignableFrom(currentType)
							)
						{
							var pluginFactory = (IPluginFactory)Activator.CreateInstance(currentType);
							pluginFactories.Add(pluginFactory);
						}
				}
				catch { }
			foreach (string subDirectoryPath in Directory.GetDirectories(directoryPath))
				LoadPluginFactories(subDirectoryPath, pluginFactories);
		}
	}
}
